<template>
  <div id="questionsView">
    <!-- 搜索区域（与首页样式一致） -->
    <div class="search-container">
      <div class="search-bar">
        <input
          type="text"
          v-model="searchParams.title"
          placeholder="请输入题目名称"
          class="search-input"
        />
        <input
          type="text"
          v-model="searchParams.tagsInput"
          placeholder="请输入标签（多个用逗号分隔）"
          class="search-input"
        />
        <button class="search-btn" @click="doSubmit">搜索</button>
      </div>
    </div>

    <a-divider size="0" />

    <!-- 题目列表表格 -->
    <a-table
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total,
      }"
      @page-change="onPageChange"
    >
      <template #tags="{ record }">
        <a-space wrap>
          <a-tag v-for="(tag, index) of record.tags" :key="index" color="green">
            {{ tag }}
          </a-tag>
        </a-space>
      </template>
      <template #acceptedRate="{ record }">
        {{
          `${
            record.submitNum
              ? ((record.acceptedNum / record.submitNum) * 100).toFixed(1)
              : "0.0"
          }% (${record.acceptedNum}/${record.submitNum})`
        }}
      </template>
      <template #createTime="{ record }">
        {{ moment(record.createTime).format("YYYY-MM-DD") }}
      </template>
      <template #optional="{ record }">
        <a-space>
          <button class="start-btn" @click="toQuestionPage(record)">
            做题
          </button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect, computed } from "vue";
import {
  Question,
  QuestionControllerService,
  QuestionQueryRequest,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import moment from "moment";

// 表格引用
const tableRef = ref();

// 题目列表数据
const dataList = ref<Question[]>([]);
const total = ref(0);

// 搜索参数（适配文本输入框）
const searchParams = ref<QuestionQueryRequest & { tagsInput: string }>({
  title: "",
  tags: [],
  tagsInput: "", // 用于文本框输入
  pageSize: 8,
  current: 1,
});

// 监听标签输入框变化，自动分割为数组
watchEffect(() => {
  if (searchParams.value.tagsInput) {
    searchParams.value.tags = searchParams.value.tagsInput
      .split(",")
      .map((tag) => tag.trim())
      .filter(Boolean);
  } else {
    searchParams.value.tags = [];
  }
});

// 加载题目列表
const loadData = async () => {
  try {
    const res = await QuestionControllerService.listQuestionVoByPageUsingPost(
      searchParams.value
    );
    if (res.code === 0) {
      dataList.value = res.data.records || [];
      total.value = res.data.total || 0;
    } else {
      message.error("加载失败：" + res.message);
    }
  } catch (error) {
    message.error("请求异常，请重试");
  }
};

// 页面加载时初始化数据
// onMounted(() => {
//   loadData();
// });
// 在浏览页面的onMounted中添加（用于接收主页面传递的参数）
onMounted(() => {
  // 从URL中获取查询参数
  const query = router.currentRoute.value.query;
  if (query.title) {
    searchParams.value.title = query.title as string;
  }
  if (query.tagsInput) {
    searchParams.value.tagsInput = query.tagsInput as string;
  }
  loadData();
});

// 搜索提交
const doSubmit = () => {
  searchParams.value.current = 1; // 重置页码
  loadData();
};

// 分页变化
const onPageChange = (page: number) => {
  searchParams.value.current = page;
  loadData();
};

// 表格列配置
const columns = [
  {
    title: "题号",
    dataIndex: "id",
    width: 80,
  },
  {
    title: "题目名称",
    dataIndex: "title",
    width: 240,
  },
  {
    title: "标签",
    slotName: "tags",
    width: 200,
  },
  {
    title: "通过率",
    slotName: "acceptedRate",
    width: 160,
  },
  {
    title: "创建时间",
    slotName: "createTime",
    width: 120,
  },
  {
    title: "操作",
    slotName: "optional",
    width: 120,
  },
];

// 路由跳转
const router = useRouter();
const toQuestionPage = (question: Question) => {
  router.push(`/view/question/${question.id}`);
};
</script>

<style scoped>
#questionsView {
  max-width: 1280px;
  margin: 0 auto;
  padding: 20px;
}

/* 搜索区域样式（与首页保持一致） */
.search-container {
  padding: 15px 0;
  background-color: #f8f9fa;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  max-width: 800px;
  margin: 0 auto;
}

/* 椭圆形搜索框（与首页样式统一） */
.search-input {
  height: 40px;
  padding: 0 1rem;
  border: 1px solid #ddd;
  border-radius: 20px; /* 椭圆形 */
  flex: 1;
  outline: none;
  font-size: 0.9rem;
  transition: border 0.3s;
}

.search-input:focus {
  border-color: #4cd964; /* 聚焦时绿色边框 */
}

/* 椭圆形提交按钮（灰底绿字，与首页一致） */
.search-btn {
  height: 40px;
  padding: 0 1.5rem;
  border: none;
  border-radius: 20px; /* 椭圆形 */
  background-color: #f0f0f0; /* 灰底 */
  color: #4cd964; /* 绿字 */
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.3s;
}

.search-btn:hover {
  background-color: #e0e0e0;
  color: #2ecc71;
}

/* 做题按钮样式（绿色白底，与首页一致） */
.start-btn {
  padding: 0.5rem 1.5rem;
  border: 2px solid #2ecc71; /* 绿色边框 */
  border-radius: 8px;
  background-color: white; /* 白底 */
  color: #2ecc71; /* 绿字 */
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 6px;
}

.start-btn:hover {
  background-color: #2ecc71;
  color: white;
}

/* 表格样式调整 */
::v-deep .arco-table-th {
  background-color: #fafafa;
}

::v-deep .arco-table-row:hover {
  background-color: #f5fff7;
}

/* 响应式调整（与首页一致） */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
    gap: 10px;
    padding: 0 15px;
  }

  .search-input,
  .search-btn {
    width: 100%;
  }
}
</style>
